import { useEffect, useState } from "react"
import { fetchArticleDetailAPI } from "@/apis/article"
import type { DetailDataType } from "@/apis/article"
import { useNavigate, useSearchParams } from "react-router-dom"
import { NavBar } from "antd-mobile"

const Detail = () => {
	const [detail, setDetail] = useState<DetailDataType | null>(null)
	// 获取路由参数
	const [params] = useSearchParams()
	const id = params.get("id")

	useEffect(() => {
		const getDetail = async () => {
			// 获取文章详情
			try {
				const res = await fetchArticleDetailAPI(id!)
				setDetail(res.data.data)
			} catch (error) {
				console.log(error)
				throw new Error("fetch detail error")
			}
		}
		getDetail()
	}, [id])

	const navigate = useNavigate()
	const back = () => {
		navigate(-1)
	}

	// 数据返回之前，使用loading渲染占位
	if (!detail) {
		return <div>this is loading...</div>
	}

	return (
		<div>
			<NavBar onBack={back}>{detail?.title}</NavBar>
			<div dangerouslySetInnerHTML={{ __html: detail?.content }}></div>
		</div>
	)
}

export default Detail
